package com.example.demo01.utils;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 提供天地图地理编码方法的工具类
 * */
public class TDUUtils {

    @Autowired
    private static CloseableHttpClient httpClient;//请求体
    @Autowired
    private static RequestConfig requestConfig;



    /**
     * @param address 目标地址名称
     * @return 包含经纬度信息的json字符串
     * */
    public static String geoCodeByAddress(String address){
        //设置请求参数
        /**
         * http://api.tianditu.gov.cn/geocoder?
         * ds={地名}
         * &tk=825fe12904c410012af61f3da2784af1
         * */
        CloseableHttpResponse httpResponse=null;//响应体
        HttpGet httpGet;//get请求
        URIBuilder uriBuilder;//网络资源路径
        String resInfo="";
        try{
            //实例化资源路径
            uriBuilder=new URIBuilder("http://api.tianditu.gov.cn/geocoder");
            //设置参数
            uriBuilder.setParameter("ds",address);
            uriBuilder.setParameter("tk", "825fe12904c410012af61f3da2784af1");
//            System.out.println(uriBuilder.toString());
            //实例化请求体
            httpClient= HttpClients.createDefault();
            //实例化get请求
            httpGet=new HttpGet(uriBuilder.build());
            //配置信息
            httpGet.setConfig(requestConfig);
            //设置请求头，模拟浏览器发送请求
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:0.9.4)");
            //通过get请求，实例化响应体
            httpResponse = httpClient.execute(httpGet);
            //判断状态码是否正常:	0：正常返回，101：结果为空，404：出错。
            if (httpResponse.getStatusLine().getStatusCode()==200){
                //获取响应结果
                resInfo = EntityUtils.toString(httpResponse.getEntity(), "utf8");
//                System.out.println(resInfo);
                return resInfo;
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接资源
            if (httpResponse!=null)
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (httpClient!=null)
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return resInfo;
    }

}
